import base64
import requests

# 基础 URL
BASE_URL = "https://httpbin.org"

# 用户名和密码
USER = "testuser"
PASSWORD = "testpass"
# USER = "wronguser"
# PASSWORD = "wrongpass"

# GET: /hidden-basic-auth/{user}/{passwd}
# Prompts the user for authorization using HTTP Basic Auth.
# parameters: user, passwd; string, (path)
# responses: 200(Successful authentication), 401(Unsuccessful authentication)
def hidden_basic_auth():
    # 构造 Basic Authentication 的 Authorization 头
    auth_header = base64.b64encode(f"{USER}:{PASSWORD}".encode()).decode()
    # print("Authorization Header:", auth_header) # Authorization Header: dGVzdHVzZXI6dGVzdHBhc3M=
    headers = {"Authorization": f"Basic {auth_header}"}

    # 1. 测试有效的用户名和密码
    valid_url = f"{BASE_URL}/hidden-basic-auth/{USER}/{PASSWORD}"
    valid_response = requests.get(valid_url, headers=headers)
    print("Valid Auth Response:", valid_response.json())

    # 2. 测试无效的用户名和密码
    invalid_auth_header = base64.b64encode("wronguser:wrongpass".encode()).decode()
    # print("Invalid Auth Header:", invalid_auth_header)      # Invalid Auth Header: d3Jvbmd1c2VyOndyb25ncGFzcw==
    invalid_headers = {"Authorization": f"Basic {invalid_auth_header}"}
    invalid_url = f"{BASE_URL}/hidden-basic-auth/{USER}/{PASSWORD}"
    invalid_response = requests.get(invalid_url, headers=invalid_headers)
    print("Invalid Auth Response:", invalid_response.status_code)

# 运行测试
hidden_basic_auth()
